<template>
  <div class="counter-component">
      <div class="counter-btn" @click="mins">-</div>
      <div class="counter-show">
          <input type="text" v-model="number" @keyup="inputHandler"/>
      </div>
      <div class="counter-btn" @click="maxs">+</div>
  </div>
</template>

<script>
export default {
    name:'counter',
    data(){
        return{
        //初始化number 就是input里面的值 相当于this.$refs.number.value
        number:1
        }
    },
    //因为input里面的值是父亲传过来的所以我们使用父传子 props
    props:
        {
            max:{
                type:Number,
                default:5
            },
            min:{
                type:Number,
                default:1
            }
        },
    methods:{
        maxs:function(){
            if(this.number >= this.max){//this.max 指的是父亲传过来的数据
                return;
            }
         this.number++;
         //子组件传值给父组件
         this.$emit('counter',this.number);
         //vuex调用要改变的组件方法
         this.$store.dispatch('updateOrder',["counter",this.number])
        },
         mins:function(){
             if(this.number <= this.min){
                 return;
             }
          this.number--;
          //子组件传值给父组件
         this.$emit('counter',this.number);
          //vuex调用要改变的组件方法
         this.$store.dispatch('updateOrder',["counter",this.number])
            },
        inputHandler(){
           
            //\D 非数字
            let fix;
            if(typeof this.number === "string"){
               
                fix = Number(this.number.replace(/\D/g,""));
                 console.log(this.number);
            }else{
                fix = this.number //0
            }
            if(fix > this.max || fix < this.min){
                //把最小的给他
                fix = this.min
            }
            this.number = fix
            console.log(fix);
            //子组件传值给父组件
         this.$emit('counter',this.number);
          //vuex调用要改变的组件方法
         this.$store.dispatch('updateOrder',["counter",this.number])
        }
        
    }
}
</script>

<style scoped>
.counter-component{
    position: relative;
    display:inline-block;
    overflow: hidden;
    vertical-align:middle;
}
.counter-show{width:30px;float:left;margin:0 10px;}
.counter-show input{float:left;width:30px;text-align:center;}
.counter-btn{width:20px;height:20px;line-height:20px;border:1px solid #ccc;text-align:center;float:left;}
</style>
